<template>
  <div>
    <el-upload
      class="avatar-uploader"
      :headers="importHeaders"
      :action="`${BASEURL}/attachment/upload`"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :show-file-list="false"
    >
      <img v-if="imgUrl" :src="imgUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      <p>上传说明图片</p>
    </el-upload>
  </div>
</template>
<script>
import { defineComponent, ref, reactive, computed } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from '@element-plus/icons-vue';
import { useStore } from "vuex";
export default defineComponent({
  name: "MediaUpload",
  props: {
    modelValue: {
      // 文件地址
      type: String,
      default: ''
    },
    name: {
      // 文件名称
      type: String,
      default: ''
    }
  },
  emits: ['save','update:modelValue','update:name'],
  components: { Plus },
  setup(props, { emit }) {
    const store = useStore()
    const imgUrl = computed({
      get: () => props.modelValue,
      set: (val) => emit("update:modelValue", val),
    })
    const imgName = computed({
      get: () => props.name,
      set: (val) => emit("update:name", val),
    })
    const beforeUpload = (file) => {
        const isLt2M = file.size / 1024 / 1024 <= 5
        if (!isLt2M) {
            this.$message.error('上传文件大小不能超过 5MB!')
        }
        return isLt2M
    }
    const importHeaders = ref({
      Authorization: store.getters.token,
      ORG: store.getters.currentOrgId
    });
    const BASEURL = ref(import.meta.env.VITE_APP_BASE_API);
    // 成功
    const handleSuccess = ({status,data,message}) => {

      if (status === 200) {
        // 请求成功 上传成功
        emit("update:modelValue", data.fileUrl)
        emit("update:name", data.fileName)
        ElMessage.success("上传成功");
      } else {
        // 请求成功 上传失败
        ElMessage.error(message);
      }
    }
    return {
      BASEURL,
      importHeaders,
      imgUrl,
      beforeUpload,
      handleSuccess
      
    };
  },
});
</script>

<style scoped>
.avatar-uploader {
  color: #2E69EB;
}
.avatar-uploader .avatar {
  width: 117px;
  height: 117px;
  display: block;
}
</style>

<style scoped>
.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  height: 117px;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  margin-top: 10px;
  font-size: 28px;
  color: #2E69EB;
  width: 117px;
  height: 70px;
  text-align: center;
}
</style>